package main

import (
	"crypto/rand"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math/big"
	"net/http"
	"net/http/cookiejar"
	"net/url"
	"os"
	"strings"
	"time"
)

var userMap = map[string]string{
	"馒头": "oioPov5uYmrDMxCV382mocv7vbRk",
	"重剑": "oioPov8QOi-XvixShNsck9L_HRt8",
}

const (
	getCookieURL = "https://vip1.i-h5.cn/lq_game/18_2/Feb_Tianxiasan/weixin.php"
	shareURL     = "https://vip1.i-h5.cn/lq_game/18_2/Feb_Tianxiasan/api.php?a=submit"
)

func main() {
	for _, v := range []string{"重剑", "馒头"} {
		sessid, err := getPhpSessID()
		if err != nil {
			panic(err)
		}
		httpDoOther(sessid, v)
	}
}

func getPhpSessID() (string, error) {
	jar, _ := cookiejar.New(nil)
	client := http.Client{
		Jar: jar,
	}

	req, err := http.NewRequest(http.MethodGet, getCookieURL, nil)
	req.Header.Set("Host", "vip1.i-h5.cn")
	req.Header.Set("accept", "*/*")
	req.Header.Set("Accept-Encoding", "gzip, deflate")
	req.Header.Set("Connection", "keep-alive")
	req.Header.Set("Accept-Language", "zh-CN,zh;q=0.8,en-us;q=0.6,en;q=0.5;q=0.4")
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.691.400 QQBrowser/9.0.2524.400")

	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	u, err := url.Parse("https://vip1.i-h5.cn")
	if err != nil {
		return "", err
	}
	cookies := client.Jar.Cookies(u)
	for i := range cookies {
		if cookies[i].Name == "PHPSESSID" {
			return cookies[i].Value, nil
		}
	}
	return "", nil
}

func httpDoOther(sessid, userName string) {
	score := getRadomScore()
	readerString := fmt.Sprintf("score=%d&share_id=%s", score, userMap[userName])
	reader := strings.NewReader(readerString)
	req, err := http.NewRequest(http.MethodPost, shareURL, reader)
	if err != nil {
		panic(err)
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Host", "vip1.i-h5.cn")
	req.Header.Set("accept", "*/*")
	req.Header.Set("Origin", "https://vip1.i-h5.cn")
	req.Header.Set("Referer", "https://vip1.i-h5.cn/lq_game/18_2/Feb_Tianxiasan/index.html")
	req.Header.Set("Accept-Encoding", "gzip, deflate")
	req.Header.Set("Connection", "keep-alive")
	req.Header.Set("Accept-Language", "zh-CN,zh;q=0.8,en-us;q=0.6,en;q=0.5;q=0.4")
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.691.400 QQBrowser/9.0.2524.400")

	req.AddCookie(&http.Cookie{
		Name:  "PHPSESSID",
		Value: sessid,
	})

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Print(err.Error())
		return
	}
	ct, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		panic(err)
	}

	dateString := time.Now().Format("2006年01月02日")

	f, err := os.OpenFile("程序执行结果.txt", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
	defer f.Close()
	res, err := decodeResult(ct)
	if err != nil {
		result := fmt.Sprintf("%s: 您尝试为%s添加%d个积分, 结果: 失败, 原因: %s, 请稍后重新尝试;\n", dateString, userName, score, err.Error())
		f.WriteString(result)
		return
	}
	if res.Code != "1" {
		result := fmt.Sprintf("%s: 您尝试为%s添加%d个积分, 结果: 失败, 原因: %s, 请稍后重新尝试;\n", dateString, userName, score, res.Info)
		f.WriteString(result)
		return
	}
	if res.Result.Status != "1" {
		result := fmt.Sprintf("%s: 您尝试为%s添加%d个积分, 结果: 失败, 原因: %s, 请稍后重新尝试;\n", dateString, userName, score, res.Result.Msg)
		f.WriteString(result)
		return
	}

	result := fmt.Sprintf("%s: 您尝试为%s添加%d个积分, 结果: 成功;\n", dateString, userName, score)
	f.WriteString(result)
}

func getRadomScore() int64 {
	return 1500 + getRadomInt(40)
}

func getRadomInt(max int64) int64 {
	nBig, err := rand.Int(rand.Reader, big.NewInt(max))
	if err != nil {
		panic(err)
	}
	return nBig.Int64()
}

type result struct {
	Code   string `json:"code"`
	Info   string `json:"info"`
	Result struct {
		Status string `json:"status"`
		Msg    string `json:"msg"`
	} `json:"result"`
}

func decodeResult(data []byte) (*result, error) {
	var r result
	if err := json.Unmarshal(data, &r); err != nil {
		return nil, err
	}

	return &r, nil
}
